<template>
  <div class="pt-8 pr-16">
    <el-form ref="form" :model="form" :rules="rules" label-width="160px">
      <el-form-item label="原密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="password_new">
        <el-input type="password" v-model="form.password_new"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="password_new2">
        <el-input type="password" v-model="form.password_new2"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确认</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.form.password_new2 !== "") {
          this.$refs.form.validateField("validatePass2");
        }
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password_new) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      form: {
        password: "",
        password_new: "",
        password_new2: "",
      },
      rules: {
        password_new: [{ validator: validatePass, trigger: "blur" }],
        password_new2: [{ validator: validatePass2, trigger: "blur" }],
        password: [{ requied: true, trigger: "blur" }],
      },
    };
  },
  methods: {
    onSubmit() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        this.axios
          .post("/admin/updatePwd", {
            newPwd: this.form.password_new,
            newPwdRe: this.form.password_new2,
            oldPwd: this.form.password,
          })
          .then((res) => {
            console.log("res", res);
            if (res.retCode != 0) {
              return this.$message.error(res.retCode);
            }
            this.form = {
              password: "",
              password_new: "",
              password_new2: "",
            };
            this.$message.success("操作成功!");
          });
      });
    },
  },
};
</script>

<style>
</style>